/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.db;

/**
 * Setting.java
 * This class holds connections, if connection is broken then it recreates it
 */

import java.sql.*;
import java.io.*;
import java.util.*;

import blueprint4j.utils.*;

public class Setting extends Entity {

	static String VERSION = "$Id: Setting.java,v 1.4 2004/09/14 13:55:09 travisb Exp $";

	public static final String TABLE_NAME = "d_settings";
	public FieldAutoId setting_id = new FieldAutoId("setting_id", 0, "The Record Identifier", this);
	public TableName table_name = new TableName(TABLE_NAME, this);
	public FieldString name = new FieldString("name",Field.FIELD_NOT_NULL | Field.FIELD_KEY, "name of this setting",100, this);
	public FieldString value = new FieldString("value",Field.FIELD_NOT_NULL, "value of this setting", 200,this);

	public Setting() {super();}

	public Setting (DBConnection connection) throws DataException, SQLException {
		super(connection);
	}

	public Setting (DBConnection connection, ResultSet result_set)
	throws DataException, SQLException {
		super(connection);
		load(result_set);
	}

	public Entity getNewInstance() {
		return new Setting();
	}

	public String getVersionString() {
		return VERSION;
	}
	
	public static Setting getAllSettings(DBConnection connection)
	throws DataException, SQLException {
		return (Setting) new Setting(connection).find("1=1");
	}

	public static Setting findSetting(DBConnection connection, String name)
	throws DataException, SQLException {
		return (Setting) new Setting(connection).find("name = '" + name + "'");
	}

	/*
	static boolean doesTableExist(DBConnection connection) {
		try {
			Statement statement = connection.createStatement();
			ResultSet rs = statement.executeQuery("select * from " + TABLE_NAME);
			boolean answer = rs.next();
			statement.close();
			return answer;
		} catch (SQLException sqle) {
			return false;
		}
	}

	private static int getVersion(DBConnection connection, String db_version_prefix)
	throws SQLException, DataException {
		if (!doesTableExist(connection)) {
			return -1;
		}
		Setting setting = Setting.findSetting(connection, db_version_prefix);
		if (setting == null) {
			return -1;
			//throw new DataException("Could not retrieve dataversion ["+db_version_prefix+"] of db_tools package");
		}
		return Integer.parseInt(setting.value.get());
	}

	private static void executeScript(DBConnection connection, InputStream stream)
	throws SQLException, IOException, DataException {
		Statement statement = connection.getDBConnection().createStatement();
		// Load the stream as a string
		byte buffer [] = new byte [1024];
		String str_buffer = "";
		while (stream.available() > 0) {
			int r = stream.read(buffer);
			if (r != -1) {
				str_buffer += new String(buffer, 0, r);
			}
		}
		StringTokenizer tokenizer = new StringTokenizer(str_buffer, ";");
		for (;tokenizer.hasMoreTokens();) {
			String sql = tokenizer.nextToken();
			if (sql != null && sql.trim().length() > 0) {
				Log.trace.out("UPDATE DATABASE\t"+sql);
				statement.execute(sql);
			}
		}
	}*/


	/*
	 * Get the current version of specified package of the db and upgrade
	 *
	private static void upgradeNow(DBConnection connection, String db_verion_prefix)
	throws SQLException, DataException, IOException {
		try {
			int current_version = DBTools.getSettingsStore().getInt(db_verion_prefix, -1);
			// upgrade all international scripts
			for (int i = current_version + 1;;i++) {
				InputStream stream = ClassLoader.getSystemResourceAsStream("sql/" + db_verion_prefix + i + ".sql");
				if (stream != null) {
					DBTools.getSettingsStore().setInt(db_verion_prefix, i);
					executeScript(connection, stream);
					connection.commit();
				} else {
					break;
				}
			}
		} catch (SQLException sqle) {
			throw sqle;
		}
	}

	/*
	 * Get the current version of db_tools of the db and upgrade
	 *
	public static void upgrade(DBConnection connection)
	throws SQLException, DataException, IOException {
		for (int i = 0;i < upgrades.size();i++) {
			upgrade(connection, upgrades.get(i));
		}
		upgrades = new ArrayList<String>();
	}

	public static void upgrade(DBConnection connection,String db_version_prefix) {
		if (true) return;
		/*
		try {
			// if the connection pool is active then do upgrade now, else add to a vector
			if (connection != null) {
				upgradeNow(connection.getLocalConnection(), db_version_prefix);
			} else {
				upgrades.add(db_version_prefix);
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}*/
	//}
}
